package com.xky.ui.module.productManagement;

import com.xky.pojo.ProductCategories;
import com.xky.ui.module.productManagement.select.SelectCateGory;
import lombok.Data;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.ExecutionException;

import static com.xky.ui.main.MainView.*;
@Data
public class ProductCategoryInfo {
    private static JTable categoryTable;
    private static JPanel homePanel;

    /**
     * 显示商品分类信息页面
     */
    public static void showCategoryInfoPage() {
        // 创建商品分类信息面板
        JPanel categoryInfoPanel = ProductCategoryMassage.createCategoryPanel(com.xky.ui.module.productManagement.ProductCategoryInfo::refreshCategoryData);

        // 获取表格组件
        Component[] components = ((JScrollPane)categoryInfoPanel.getComponent(1)).getViewport().getComponents();
        if (components.length > 0 && components[0] instanceof JTable) {
            categoryTable = (JTable) components[0];
        }

        // 更新右侧面板
        rightPanel.removeAll();
        rightPanel.add(categoryInfoPanel, BorderLayout.CENTER);
        rightPanel.revalidate();
        rightPanel.repaint();

        // 注册刷新操作
        registerRefreshAction("商品分类", ProductCategoryInfo::refreshCategoryData);

        // 立即刷新一次
        refreshCategoryData();
    }

    /**
     * 刷新商品分类数据
     */
    static void refreshCategoryData() {
        new SwingWorker<List<ProductCategories>, Void>() {
            @Override
            protected List<ProductCategories> doInBackground() {
                DefaultTableModel model = (DefaultTableModel) categoryTable.getModel();
                model.setRowCount(0);
                return SelectCateGory.selectAllCateGory();
            }

            @Override
            protected void done() {
                try {
                    List<ProductCategories> categoryList = get();
                    if (categoryTable != null) {
                        ProductCategoryMassage.updateTableData(categoryTable, categoryList);
                        rightPanel.repaint();
                    }
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "刷新失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }.execute();
    }
}
